import { defineComponent,PropType ,ref,CSSProperties, reactive, Ref, onMounted} from "vue"
import { AgGridVue } from "ag-grid-vue3";
import { GridOptions } from 'ag-grid-community';
import classes from "./index.module.scss"
import { ElPagination, ElButton } from "element-plus"
import { Emiter, joinMacrotask, joinMicrotask } from "@Tea/utils";
import { ChooseRequired } from "@Tea/model";
import "./cover.scss"
import "ag-grid-community/styles/ag-grid.css"; // Core grid CSS, always needed
import "ag-grid-community/styles/ag-theme-alpine.css"; // Optional theme CSS

type PaginationConfig = {
  tableName: string,
  pageSizes: number[]
}

export type GridType<TData = any> = ChooseRequired<GridOptions<TData>, "columnDefs"> 

function usePagination(config: PaginationConfig) {
   // 注册订阅事件
  const emiter = Emiter.getInstance()
  const currentPage = ref(1)
  const pageSize = ref(config?.pageSizes[0] || 100)
  const total = ref(0)
  const pageSizes = ref(config.pageSizes || [100, 200, 300, 400])

  const handleSizeChange = (val: number) => {
    pageSize.value = val
    emiter.emit(config.tableName, `onSearch`)
  }

  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    emiter.emit(config.tableName, `onSearch`)
  }

 
  
  // 重置页数
  emiter.on(config.tableName, `resetCurPage`, () => {
      currentPage.value = 1
  })

  //获取currentPage pageSize
  emiter.on(config.tableName, `getCurAndSize`, () => ({
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }))

  //设置条数
  emiter.on(config.tableName, `setTotal`, (num: number) => {
    total.value = num
  })

  // 设置PageSize 
  emiter.on(config.tableName, 'setPageSize', (sizes: number[])=> {
    pageSizes.value = sizes
  })

  return { currentPage, pageSize, pageSizes, total, handleSizeChange, handleCurrentChange }
}

function useAgGrid(config: GridType, tableName:string) {
  const gridApi = ref(null); // Optional - for accessing Grid's API
  const gridColumnApi = ref(null)
  // Obtain API from grid's onGridReady event
  const onGridReady = (params) => {

    gridApi.value = params.api;
    gridColumnApi.value = params.columnApi
    
  };

  // Set rowData to Array of Objects, one Object per Row
  const rowData = ref(config.rowData || []); 

  // Each Column Definition results in one Column.
  //const columnDefs = reactive<GridType["columnDefs"]>([]);

  // DefaultColDef sets props common to all Columns
  const defaultColDef:GridType["defaultColDef"] = {
    sortable: true,
    filter: true,
  };

  const gridOptions: Omit<GridOptions, "rowData"> & { rowData: Ref<GridOptions["rowData"][]> } = {
    enableRangeSelection: true,
    enableRangeHandle: true,
    suppressMultiRangeSelection: true,
    columnDefs: reactive<GridType["columnDefs"]>(config.columnDefs) as GridType["columnDefs"],
    rowData: rowData,
    onGridReady,
    defaultColDef: Object.assign(defaultColDef, config.defaultColDef || {})
  };
  
  const emitter = Emiter.getInstance()
  emitter.on(tableName, "getGridApi", () => gridApi.value)
  emitter.on(tableName, "getGridColumnApi", () => gridColumnApi.value)
  emitter.on(tableName, "setRowData", (data: any[]) => {
    rowData.value = data
  }) 
  return  gridOptions
}



export default defineComponent({
  props: {
    tableClass: String,
    tableStyle: {
      type: Object as PropType<CSSProperties>
    },
    initPagination: {
      type: Boolean,
      default: true
    },
    pagintionAttr: {
      type: Object as PropType<Omit<PaginationConfig, "tableName">>,
      default: {
       pageSizes: [100, 200, 300, 400]
      }
    },
    tableName: {
      type: String,
      required: true,
    },
    gridAttr: {
      type: Object as PropType<GridType>,
      required: true
    },
  },
  setup(props, ctx) {
    const {
      currentPage, pageSize, total, pageSizes,
      handleSizeChange, handleCurrentChange
    } = usePagination({
      tableName: props.tableName,
      pageSizes: props.pagintionAttr.pageSizes
    })

    const gridOptions = useAgGrid(props.gridAttr, props.tableName)
    onMounted(() => {
      console.log(324);
      
    })    
    return () => {
      return (
        <div class={`${props.tableClass || ''} ${classes.table} m-window`} style={props.tableStyle || {}}>
          <div class={`ag-theme-balham ${classes.agGrid}`} style={{ flex: 1, width: "100%" }}>
            <AgGridVue
              class="ag-theme-alpine"
              style="height: 500px"
              {...{
                ...gridOptions,
                rowData: gridOptions.rowData.value 
              }}
            />
          </div>
          {
            props.initPagination && (
              <div class={`m-top ${classes.pagination}`}>
                <ElPagination
                  v-model:pageSize={pageSize.value}
                  v-model:currentPage={currentPage.value}
                  layout="total,sizes, pager,jumper"
                  total={total.value}
                  pageSizes={pageSizes.value}
                  background
                  small
                  {
                  ...{
                    "onSize-change": handleSizeChange,
                    "onCurrent-change": handleCurrentChange
                  }
                  }
                />
              </div>
            )}
        </div>
      )
    }
  },
});